package thread;

public class SyncDemo {
    public static void main(String[] args) {
         /*
        shop shop = new shop();

        Thread t1 = new Thread("wkj"){
          public void run(){
              shop.buy();
          }
        };
        Thread t2 = new Thread("fcq"){
            public void run(){
                shop.buy();
            }
        };
        t1.start();
        t2.start();
         */
        shop shop1 = new shop();
        shop shop2 = new shop();
        /*
        Thread t1 = new Thread("wkj"){
          public void run(){
              shop1.buy();
          }
        };
        Thread t2 = new Thread("fcq"){
          public void run(){
              shop2.buy();
          }
        };
         */
        Thread t1 = new Thread(shop1::buy);
        Thread t2 = new Thread(shop2::buy);
        t1.start();
        t2.start();
    }
}
class shop{
    //public synchronized void buy(){//在方法上同步监视（加锁），范围比较大
        public  void buy(){
        try {
            Thread t = Thread.currentThread();
            System.out.println(t.getName()+"正在挑衣服");
            Thread.sleep(3000);
            /*
            同步监视
             */
            //synchronized (new object){//永远不能用实例化对象作为同步监视器对象，一定无效
            //synchronized (123){//同步监视器对象一定是引用对象
            //synchronized ("abc"){//虽然可以锁上，但"abc"并不适合锁对象
            synchronized (this){//同步监视块，缩小了监视范围
               System.out.println(t.getName()+"正在试衣服");
               Thread.sleep(3000);
            }
            System.out.println(t.getName()+"结账离开了");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }
}





